package org.vehicle.task;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.vehicle.entity.PersonInfo;
import org.vehicle.entity.TempPersonInfo;
import org.vehicle.entity.VehicleInfo;
import org.vehicle.service.PersonInfoService;
import org.vehicle.service.TempPersonInfoService;
import org.vehicle.service.VehicleInfoService;
import org.vehicle.service.redis.RedisService;
import org.vehicle.util.CommonUtil;
import org.vehicle.util.FtpUtil;

@Component  
public class personTask{  
	
	private static Logger logger = LogManager.getLogger(personTask.class.getName());
	
	@Autowired
	private TempPersonInfoService tempPersonInfoService;
	@Autowired
	private PersonInfoService personInfoService;
	@Autowired
	private VehicleInfoService vehicleInfoService;
	@Autowired
	private RedisService redisService;
	
    @Scheduled(cron="*/5 * *  * * ? ")   //每5秒执行一次      
    public void personAddTask(){
    	FTPClient ftpClient=null;
    	try{
    		SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
    		List<TempPersonInfo> TempPersonInfoList=tempPersonInfoService.findAllTempPersonInfo();
        	if(TempPersonInfoList==null){
        		return;
        	}
        	for(TempPersonInfo tempPersonInfo:TempPersonInfoList){
        		try{
        			Map<String, Object> paramMap=new HashMap<String, Object>();
        			paramMap.put("deviceSN", tempPersonInfo.getDeviceCode());
        			VehicleInfo vehicleInfo=vehicleInfoService.findVehicleInfoByCode(paramMap);
        			if(tempPersonInfo.getPersonType()==3){
        				Map<String,Object> countParamMap=new HashMap<String,Object>();
        				countParamMap.put("checkType", 2);
        				countParamMap.put("vehicleInfoId", vehicleInfo.getVehicleInfoId());
        				vehicleInfoService.updateCountById(countParamMap);
        				tempPersonInfo.setState(0);
            			tempPersonInfoService.updateByPrimaryKeySelective(tempPersonInfo);
        				continue;
        			}
        			PersonInfo personInfo=new PersonInfo();
        			personInfo.setCertificateCode(tempPersonInfo.getCertificateCode());
        			personInfo.setName(tempPersonInfo.getPersonName());
        			personInfo.setGender(tempPersonInfo.getGender());
        			personInfo.setBirthday(tempPersonInfo.getBirthday());
        			personInfo.setNationality(tempPersonInfo.getNationality());
        			personInfo.setAddress(tempPersonInfo.getAddress());
        			personInfo.setCertificateCodeEffectiveDate(tempPersonInfo.getCertificateCodeEffectiveDate());
        			personInfo.setSignOrganization(tempPersonInfo.getSignOrganization());
        			if(tempPersonInfo.getPersonType()==2){
        				personInfo.setPersonType(2);
        			}else{
        				personInfo.setPersonType(1);
        			}
        			personInfo.setState(1);
        			personInfo.setCreateDate(tempPersonInfo.getCreateDate());
        			PersonInfo personInfo2=null;
        			if(!StringUtils.isEmpty(personInfo.getCertificateCode())){
        				 personInfo2=personInfoService.findPersonInfoByCertificateCode(personInfo.getCertificateCode());
        			}
        			if(personInfo2==null){
        				String ftp_photoDirectory="image/" + sdf.format(new Date());
            			ftpClient=FtpUtil.connect(CommonUtil.getPropertiesParam("ftp_address"), Integer.parseInt(CommonUtil.getPropertiesParam("ftp_port")), CommonUtil.getPropertiesParam("ftp_user"), CommonUtil.getPropertiesParam("ftp_password"), ftp_photoDirectory);
            			if(!StringUtils.isEmpty(tempPersonInfo.getCertificateFaceBase64())){
            				byte[] certificateFaceBytes=Base64Utils.decodeFromString(tempPersonInfo.getCertificateFaceBase64());
                			String certificateFaceFileName=FtpUtil.generateFileName("certificateFace.jpg");
                			try(InputStream is=new ByteArrayInputStream(certificateFaceBytes)){
                				FtpUtil.upload(certificateFaceFileName, is, ftpClient);
                				personInfo.setCertificateFaceUrl(ftp_photoDirectory+"/"+certificateFaceFileName);
                			}catch (Exception e) {
                				logger.error(e);
                			}
            			}
            			if(!StringUtils.isEmpty(tempPersonInfo.getPersonFaceBase64())){
            				byte[] personFaceBytes=Base64Utils.decodeFromString(tempPersonInfo.getPersonFaceBase64());
                			String personFaceName=FtpUtil.generateFileName("certificateFace.jpg");
                			try(InputStream is=new ByteArrayInputStream(personFaceBytes)){
                				FtpUtil.upload(personFaceName, is, ftpClient);
                				personInfo.setPersonFaceUrl(ftp_photoDirectory+"/"+personFaceName);
                			}catch (Exception e) {
                				logger.error(e);
                			}
            			}
        			}else{
        				personInfo.setCertificateFaceUrl(personInfo2.getCertificateFaceUrl());
        				personInfo.setPersonFaceUrl(personInfo2.getCertificateFaceUrl());
        			}
        			String eventId=redisService.getString(vehicleInfo.getVehicleLicense()+"_eventId");
        			if(tempPersonInfo.getPersonType()==4){
        				personInfoService.addPersonInfo(personInfo, vehicleInfo,3,null,eventId);
        			}else{
        				personInfoService.addPersonInfo(personInfo, vehicleInfo,2,null,eventId);
        			}
        			tempPersonInfo.setState(0);
        			tempPersonInfoService.updateByPrimaryKeySelective(tempPersonInfo);
        		}catch(Exception e){
        			e.printStackTrace();
            		logger.error(e);
            		continue;
        		}
        	}
    	}catch(Exception e){
    		e.printStackTrace();
    		logger.error(e);
    	}finally{
    		if(ftpClient!=null){
    			try{
    				FtpUtil.closeConnection(ftpClient);
    			}catch(Exception e){
    				ftpClient=null;
    			}
    			
    		}
    	}
    }      
}  
